<template>
  <div class="panel-content">
    <div class="panel-header">
      <div class="panel-title">
        <span class="panel-icon">👥</span>
        <span>人物</span>
      </div>
      <div class="character-actions">
        <el-button size="small" type="primary" @click="addCharacter">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button size="small" type="success" @click="showBatchGenerateDialog">
          🤖 AI生成
        </el-button>
      </div>
    </div>

    <div class="characters-list" v-loading="loading" element-loading-text="正在加载人物...">
      <el-card
        v-for="character in characters"
        :key="character.id"
        class="character-item"
        shadow="hover"
      >
        <el-row :gutter="16" type="flex" justify="space-between" align="middle">
          <el-col :span="20">
            <div class="character-content" @click="editCharacter(character)">
              <div class="character-avatar">
                <img v-if="character.avatar" :src="character.avatar" />
                <div v-else class="default-avatar">{{ character.name?.charAt(0) || '？' }}</div>
              </div>
              <div class="character-info">
                <h4>{{ character.name }}</h4>
                <div class="character-meta">
                  <el-tag :type="getRoleType(character.role)" size="small">{{ getRoleText(character.role) }}</el-tag>
                  <el-tag v-if="character.gender" type="info" size="small">{{ getGenderText(character.gender) }}</el-tag>
                  <span v-if="character.age" class="age-text">{{ character.age }}岁</span>
                </div>
                <el-tooltip
                  v-if="character.personality"
                  :content="character.personality"
                  placement="right"
                  :disabled="character.personality.length <= 60"
                  effect="light"
                  :show-after="300"
                >
                  <p class="character-desc character-desc-truncated">
                    {{ character.personality.length > 60 ? character.personality.substring(0, 60) + '...' : character.personality }}
                  </p>
                </el-tooltip>
                <div class="character-tags" v-if="character.tags && character.tags.length">
                  <el-tag v-for="tag in character.tags" :key="tag" size="small">{{ tag }}</el-tag>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="character-actions">
              <el-dropdown @command="(cmd) => handleCharacterAction(cmd, character)" trigger="click">
                <el-button size="small" type="text" @click.stop>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-empty v-if="characters.length === 0" description="暂无人物设定">
        <el-button size="small" @click="addCharacter">创建第一个角色</el-button>
      </el-empty>
    </div>

    <!-- 人物编辑对话框 -->
    <el-dialog v-model="showCharacterDialog" title="编辑角色" width="700px">
      <el-form :model="characterForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="characterForm.name" />
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="characterForm.role">
                <el-option label="主角" value="protagonist" />
                <el-option label="配角" value="supporting" />
                <el-option label="反派" value="antagonist" />
                <el-option label="次要角色" value="minor" />
              </el-select>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="characterForm.gender">
                <el-radio label="male">男</el-radio>
                <el-radio label="female">女</el-radio>
                <el-radio label="other">其他</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
              <el-input-number v-model="characterForm.age" :min="0" :max="1000" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="外貌">
              <el-input v-model="characterForm.appearance" type="textarea" :rows="3" />
            </el-form-item>
            <el-form-item label="性格">
              <el-input v-model="characterForm.personality" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="背景故事">
          <div class="form-item-with-ai">
            <el-input v-model="characterForm.background" type="textarea" :rows="4" />
            <div class="ai-button-group" style="margin-top: 8px;">
              <el-button size="small" type="success" :loading="isStreaming" @click="generateCharacterAI">
                🤖 AI生成角色信息
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="characterTagInput" placeholder="输入标签后按回车" @keyup.enter="addCharacterTag">
            <template #append>
              <el-button @click="addCharacterTag">添加</el-button>
            </template>
          </el-input>
          <div v-if="characterForm.tags.length > 0" style="margin-top: 8px;">
            <el-tag
              v-for="(tag, index) in characterForm.tags"
              :key="index"
              closable
              @close="removeCharacterTag(index)"
              style="margin-right: 8px;"
            >{{ tag }}</el-tag>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCharacterDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCharacter">保存</el-button>
      </template>
    </el-dialog>

    <!-- 批量生成角色对话框 -->
    <el-dialog v-model="showBatchGenerateCharacterDialog" title="AI批量生成角色" width="900px" @close="showBatchGenerateCharacterDialog = false">
      <div class="batch-generate-content">
        <!-- 配置区域 -->
        <el-card v-if="!batchGenerating && generatedCharacters.length === 0" shadow="never" class="config-section">
          <template #header>
            <span>⚙️ 生成配置</span>
          </template>
          <el-form label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="生成数量">
                  <el-input-number v-model="batchGenerateConfig.count" :min="2" :max="10" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="角色类型">
                  <div class="character-type-options">
                    <el-checkbox v-model="batchGenerateConfig.includeMainCharacters">主角</el-checkbox>
                    <el-checkbox v-model="batchGenerateConfig.includeSupportingCharacters">配角</el-checkbox>
                    <el-checkbox v-model="batchGenerateConfig.includeMinorCharacters">次要角色</el-checkbox>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="特殊要求">
              <el-input
                v-model="batchGenerateConfig.customPrompt"
                type="textarea"
                :rows="3"
                placeholder="可选：补充风格/世界观/设定约束"
              />
            </el-form-item>

            <el-form-item label="智能分配">
              <el-checkbox v-model="batchGenerateConfig.autoAssignRoles">自动平衡角色关系和重要性</el-checkbox>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 流式生成区域 -->
        <el-card v-if="batchGenerating" shadow="never" class="streaming-section">
          <template #header>
            <span>🤖 AI正在生成角色...</span>
          </template>
          <el-skeleton :rows="6" animated />
        </el-card>

        <!-- 生成结果区域 -->
        <el-card v-if="!batchGenerating && generatedCharacters.length > 0" shadow="never" class="results-section">
          <template #header>
            <div class="results-header">
              <span>✨ 生成结果 ({{ generatedCharacters.length }}个角色)</span>
              <div class="result-actions">
                <el-button size="small" @click="() => generatedCharacters.forEach(char => char.selected = true)">全选</el-button>
                <el-button size="small" @click="() => generatedCharacters.forEach(char => char.selected = false)">全不选</el-button>
              </div>
            </div>
          </template>

          <div class="generated-characters-grid">
            <div
              v-for="character in generatedCharacters"
              :key="character.id"
              class="generated-character-card"
              :class="{ selected: character.selected !== false }"
              @click="toggleCharacterSelection(character)"
            >
              <div class="character-header">
                <div class="character-avatar-preview">
                  <div class="default-avatar">{{ character.name?.charAt(0) || '？' }}</div>
                </div>
                <div class="character-basic-info">
                  <h4>{{ character.name }}</h4>
                  <div class="character-meta">
                    <el-tag :type="getRoleType(character.role)" size="small">{{ getRoleText(character.role) }}</el-tag>
                    <el-tag type="info" size="small">{{ getGenderText(character.gender) }}</el-tag>
                    <span class="age-text">{{ character.age }}岁</span>
                  </div>
                </div>
                <div class="selection-indicator">
                  <el-icon v-if="character.selected !== false" class="selected-icon"><Check /></el-icon>
                </div>
              </div>

              <div class="character-details">
                <div class="detail-item">
                  <label>外貌：</label>
                  <p>{{ character.appearance || '暂无描述' }}</p>
                </div>
                <div class="detail-item">
                  <label>性格：</label>
                  <p>{{ character.personality || '暂无描述' }}</p>
                </div>
                <div class="detail-item">
                  <label>背景：</label>
                  <p>{{ character.background || '暂无描述' }}</p>
                </div>
                <div class="detail-item">
                  <label>标签：</label>
                  <p>{{ (character.tags || []).join('，') }}</p>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <div class="dialog-footer">
        <el-button @click="showBatchGenerateCharacterDialog = false">取消</el-button>
        <el-button
          v-if="!batchGenerating && generatedCharacters.length === 0"
          type="primary"
          @click="batchGenerateCharacters"
          :disabled="!batchGenerateConfig.includeMainCharacters && !batchGenerateConfig.includeSupportingCharacters && !batchGenerateConfig.includeMinorCharacters"
        >
          开始生成
        </el-button>
        <el-button
          v-if="batchGenerating"
          type="danger"
          :disabled="true"
        >正在生成...</el-button>
        <el-button
          v-if="!batchGenerating && generatedCharacters.length > 0"
          @click="batchGenerateCharacters"
        >重新生成</el-button>
        <el-button
          v-if="!batchGenerating && generatedCharacters.length > 0"
          type="primary"
          @click="saveGeneratedCharacters"
        >保存选中角色</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue'
import { Plus, MoreFilled, Edit, Delete, Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiService from '../services/api.js'
import { characterApi } from '../services/novelApi.js'

// 根据当前小说信息动态构建“小说基本信息”提示词
const getNovelPrompt = (novelInfo) => {
  const title = novelInfo?.title || '未命名小说'
  const genre = novelInfo?.genre || '通用小说'
  const description = novelInfo?.description || '暂无简介'
  return `=== 小说基本信息 ===\n小说标题：${title}\n小说类型：${genre}\n小说简介：${description}`
}

// Props
const props = defineProps({
  characters: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  novelId: {
    type: [String, Number],
    default: null
  },
  checkApiAndBalance: {
    type: Function,
    default: null
  },
  novelInfo: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:characters'])

// 本地状态
const showCharacterDialog = ref(false)
const characterForm = ref({
  id: null,
  name: '',
  role: 'supporting',
  gender: 'male',
  age: 25,
  appearance: '',
  personality: '',
  background: '',
  tags: [],
  avatar: ''
})
const characterTagInput = ref('')
const isStreaming = ref(false)

// 批量生成状态
const showBatchGenerateCharacterDialog = ref(false)
const batchGenerateConfig = ref({
  count: 5,
  includeMainCharacters: true,
  includeSupportingCharacters: true,
  includeMinorCharacters: true,
  customPrompt: '',
  autoAssignRoles: true
})
const batchGenerating = ref(false)
const generatedCharacters = ref([])

// 方法 - 列表行为
const addCharacter = () => {
  characterForm.value = {
    id: null,
    name: '',
    role: 'supporting',
    gender: 'male',
    age: 25,
    appearance: '',
    personality: '',
    background: '',
    tags: [],
    avatar: ''
  }
  showCharacterDialog.value = true
}

const editCharacter = (character) => {
  characterForm.value = { ...character }
  showCharacterDialog.value = true
}

const handleCharacterAction = (command, character) => {
  switch (command) {
    case 'edit':
      editCharacter(character)
      break
    case 'delete':
      deleteCharacter(character)
      break
  }
}

const saveCharacter = async () => {
  if (!characterForm.value.name.trim()) {
    ElMessage.warning('请输入角色姓名')
    return
  }
  if (!props.novelId) {
    ElMessage.error('小说信息不存在')
    return
  }

  try {
    if (characterForm.value.id) {
      const characterData = {
        name: characterForm.value.name,
        role: characterForm.value.role,
        gender: characterForm.value.gender,
        age: characterForm.value.age,
        appearance: characterForm.value.appearance,
        personality: characterForm.value.personality,
        background: characterForm.value.background,
        tags: characterForm.value.tags,
        avatar: characterForm.value.avatar
      }
      const updatedCharacter = await characterApi.updateCharacter(
        props.novelId,
        characterForm.value.id,
        characterData
      )
      const list = [...props.characters]
      const index = list.findIndex(c => c.id === characterForm.value.id)
      if (index > -1) {
        list[index] = {
          ...updatedCharacter,
          createdAt: new Date(updatedCharacter.createdAt),
          updatedAt: new Date(updatedCharacter.updatedAt)
        }
        emit('update:characters', list)
      }
      ElMessage.success('角色信息已更新')
    } else {
      const characterData = {
        name: characterForm.value.name,
        role: characterForm.value.role,
        gender: characterForm.value.gender,
        age: characterForm.value.age,
        appearance: characterForm.value.appearance,
        personality: characterForm.value.personality,
        background: characterForm.value.background,
        tags: characterForm.value.tags,
        avatar: characterForm.value.avatar
      }
      const newCharacter = await characterApi.createCharacter(props.novelId, characterData)
      const list = [
        ...props.characters,
        {
          ...newCharacter,
          createdAt: new Date(newCharacter.createdAt),
          updatedAt: new Date(newCharacter.updatedAt)
        }
      ]
      emit('update:characters', list)
      ElMessage.success('角色创建成功')
    }
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error('保存角色失败: ' + (error.message || '未知错误'))
    return
  }

  showCharacterDialog.value = false
}

const deleteCharacter = (character) => {
  ElMessageBox.confirm(`确定要删除角色《${character.name}》吗？`, '确认删除', {
    type: 'warning',
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    confirmButtonClass: 'el-button--danger'
  }).then(async () => {
    if (!props.novelId) {
      ElMessage.error('小说信息不存在')
      return
    }
    try {
      await characterApi.deleteCharacter(props.novelId, character.id)
      const list = props.characters.filter(c => c.id !== character.id)
      emit('update:characters', list)
      ElMessage.success('角色已删除')
    } catch (error) {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {})
}

// AI - 单个角色生成
const generateCharacterAI = async () => {
  if (props.checkApiAndBalance && !props.checkApiAndBalance()) return
  if (!characterForm.value.name.trim()) {
    ElMessage.warning('请先输入角色姓名')
    return
  }
  isStreaming.value = true
  try {
    const roleMap = { protagonist: '主角', supporting: '配角', antagonist: '反派', minor: '次要角色' }
    const genderMap = { male: '男', female: '女', other: '其他' }
    const prompt = `${getNovelPrompt(props.novelInfo)}\n\n=== 角色生成任务 ===\n你是一个专业的角色生成器。请为角色《${characterForm.value.name}》生成详细信息。\n【重要】严格按以下格式输出：\n\n外貌：...\n性格：...\n背景：...\n标签：标签1,标签2,标签3\n\n=== 角色基本设定 ===\n- 角色定位：${roleMap[characterForm.value.role] || '配角'}\n- 性别：${genderMap[characterForm.value.gender] || '男'}\n- 年龄：${characterForm.value.age}岁\n\n开始生成：`
    const suffix = `\n=== 重要格式要求 ===\n外貌：[详细外貌描述]\n性格：[性格特点描述]\n背景：[背景故事]\n标签：[标签1,标签2,标签3]\n必须包含以上4行，每行一个字段。`
    const promptWithFormat = prompt + suffix
    
    const fullContent = await apiService.generateTextStream(promptWithFormat, {
      maxTokens: null,
      temperature: 0.8,
      type: 'character'
    }, (chunk, content) => {
      // 实时流式更新
      const lines = content.split('\n')
      for (const line of lines) {
        const trimmed = line.trim()
        if (trimmed.startsWith('外貌：')) {
          characterForm.value.appearance = trimmed.replace('外貌：', '').trim()
        } else if (trimmed.startsWith('性格：')) {
          characterForm.value.personality = trimmed.replace('性格：', '').trim()
        } else if (trimmed.startsWith('背景：')) {
          characterForm.value.background = trimmed.replace('背景：', '').trim()
        } else if (trimmed.startsWith('标签：')) {
          const tagString = trimmed.replace('标签：', '').trim()
          if (tagString) {
            characterForm.value.tags = tagString.split(',').map(t => t.trim()).filter(t => t)
          }
        }
      }
    })
    
    // 最终完整解析
    if (fullContent) {
      const lines = fullContent.split('\n')
      for (const line of lines) {
        const trimmed = line.trim()
        if (trimmed.startsWith('外貌：')) {
          characterForm.value.appearance = trimmed.replace('外貌：', '').trim()
        } else if (trimmed.startsWith('性格：')) {
          characterForm.value.personality = trimmed.replace('性格：', '').trim()
        } else if (trimmed.startsWith('背景：')) {
          characterForm.value.background = trimmed.replace('背景：', '').trim()
        } else if (trimmed.startsWith('标签：')) {
          const tagString = trimmed.replace('标签：', '').trim()
          if (tagString) {
            characterForm.value.tags = tagString.split(',').map(t => t.trim()).filter(t => t)
          }
        }
      }
    }
    ElMessage.success('AI角色生成完成')
  } catch (error) {
    console.error('AI生成角色失败:', error)
    ElMessage.error(`角色生成失败: ${error.message}`)
  } finally {
    isStreaming.value = false
  }
}

const addCharacterTag = () => {
  const tag = characterTagInput.value.trim()
  if (tag && !characterForm.value.tags.includes(tag)) {
    characterForm.value.tags.push(tag)
    characterTagInput.value = ''
  }
}

const removeCharacterTag = (index) => {
  characterForm.value.tags.splice(index, 1)
}

// 批量生成 - 打开对话框
const showBatchGenerateDialog = () => {
  showBatchGenerateCharacterDialog.value = true
  batchGenerateConfig.value = {
    count: 5,
    includeMainCharacters: true,
    includeSupportingCharacters: true,
    includeMinorCharacters: true,
    customPrompt: '',
    autoAssignRoles: true
  }
  generatedCharacters.value = []
}

// 批量生成 - 执行
const batchGenerateCharacters = async () => {
  if (props.checkApiAndBalance && !props.checkApiAndBalance()) return
  batchGenerating.value = true
  generatedCharacters.value = []
  try {
    const types = []
    if (batchGenerateConfig.value.includeMainCharacters) types.push('主角')
    if (batchGenerateConfig.value.includeSupportingCharacters) types.push('配角')
    if (batchGenerateConfig.value.includeMinorCharacters) types.push('次要角色')
    const count = batchGenerateConfig.value.count
    const prompt = `${getNovelPrompt(props.novelInfo)}\n\n=== 角色生成任务 ===\n你是一个专业的小说角色生成器。请严格按照指定格式为上述小说生成${count}个人物角色。\n\n【重要】必须严格按照以下格式输出，不要添加任何额外的解释或文字：\n\n角色1：\n姓名：张三\n角色：主角\n性别：男\n年龄：25\n外貌：身高一米八，浓眉大眼，面容坚毅\n性格：勇敢正直，有些冲动，但心地善良\n背景：出身农家，自幼习武，立志成为英雄\n标签：主角,勇敢,正义\n\n角色2：\n姓名：李美娜\n角色：配角\n性别：女\n年龄：22\n外貌：身材娇小，长发飘逸，眼神清澈动人\n性格：温柔善良，聪明机智，偶尔有些任性\n背景：大家闺秀，从小接受良好教育，精通琴棋书画\n标签：配角,温柔,才女\n\n请完全按照以上示例格式生成${count}个角色，每个角色都必须包含：姓名、角色、性别、年龄、外貌、性格、背景、标签这8个字段。\n\n=== 生成要求 ===\n角色类型要求：${types.join('、')}\n\n请确保所有角色设定都符合小说的世界观、类型和风格特点。\n\n开始生成：\n\n=== 重要格式要求 ===\n无论上述提示词如何，你必须严格按照以下格式输出，不得有任何偏差：\n\n请生成${count}个角色，角色类型包括：${types.join('、')}\n\n角色1：\n姓名：[角色姓名]\n角色：[主角/配角/反派/次要角色]\n性别：[男/女/其他]\n年龄：[数字]\n外貌：[详细外貌描述]\n性格：[性格特点描述]\n背景：[背景故事]\n标签：[标签1,标签2,标签3]\n\n角色2：\n姓名：[角色姓名]\n角色：[主角/配角/反派/次要角色]\n性别：[男/女/其他]\n年龄：[数字]\n外貌：[详细外貌描述]\n性格：[性格特点描述]\n背景：[背景故事]\n标签：[标签1,标签2,标签3]\n\n继续按此格式直到生成完所有${count}个角色。每个角色必须包含这8个字段。角色类型应该在${types.join('、')}中选择`
    const full = await apiService.generateTextStream(prompt, {
      maxTokens: null,
      temperature: 0.8,
      type: 'batchCharacters'
    }, () => {})
    const rawBlocks = full.split(/\n\s*\n/).map(s => s.trim()).filter(Boolean)
    generatedCharacters.value = rawBlocks.map((block, idx) => {
      const lines = block.split('\n').map(l => l.trim())
      const get = (prefix) => {
        const line = lines.find(l => l.startsWith(prefix))
        return line ? line.replace(prefix, '').trim() : ''
      }
      const tags = get('标签：') ? get('标签：').split(',').map(t => t.trim()).filter(Boolean) : []
      return {
        id: Date.now() + idx,
        name: get('姓名：') || `角色${idx + 1}`,
        role: (get('角色：') || '配角').includes('主') ? 'protagonist' : (get('角色：').includes('反') ? 'antagonist' : (get('角色：').includes('次') ? 'minor' : 'supporting')),
        gender: (get('性别：') || '男').includes('女') ? 'female' : 'male',
        age: parseInt(get('年龄：').replace(/[^0-9]/g, '') || '25', 10),
        appearance: get('外貌：'),
        personality: get('性格：'),
        background: get('背景：'),
        tags,
        selected: true
      }
    })
  } catch (e) {
    console.error(e)
    ElMessage.error('批量生成失败')
  } finally {
    batchGenerating.value = false
  }
}

const toggleCharacterSelection = (character) => {
  character.selected = character.selected === false ? true : false
}

const saveGeneratedCharacters = async () => {
  if (!props.novelId) {
    ElMessage.error('小说信息不存在')
    return
  }
  const selected = generatedCharacters.value.filter(c => c.selected !== false)
  if (selected.length === 0) {
    ElMessage.warning('请至少选择一个角色')
    return
  }
  try {
    const newList = [...props.characters]
    for (const c of selected) {
      const data = {
        name: c.name,
        role: c.role,
        gender: c.gender,
        age: c.age,
        appearance: c.appearance,
        personality: c.personality,
        background: c.background,
        tags: c.tags
      }
      const saved = await characterApi.createCharacter(props.novelId, data)
      newList.push({
        ...saved,
        createdAt: new Date(saved.createdAt),
        updatedAt: new Date(saved.updatedAt)
      })
    }
    emit('update:characters', newList)
    ElMessage.success('已保存选中角色')
    showBatchGenerateCharacterDialog.value = false
  } catch (e) {
    console.error(e)
    ElMessage.error('保存失败')
  }
}

// 获取角色类型样式
const getRoleType = (role) => {
  const roleMap = {
    'protagonist': 'danger',
    'supporting': 'primary',
    'antagonist': 'warning',
    'minor': 'info'
  }
  return roleMap[role] || 'info'
}

// 获取角色类型文本
const getRoleText = (role) => {
  const roleMap = {
    'protagonist': '主角',
    'supporting': '配角',
    'antagonist': '反派',
    'minor': '次要角色'
  }
  return roleMap[role] || '配角'
}

// 获取性别文本
const getGenderText = (gender) => {
  const genderMap = {
    'male': '男',
    'female': '女',
    'other': '其他'
  }
  return genderMap[gender] || '男'
}
</script>

<style scoped>
.panel-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow: hidden;
  height: calc(100vh - 150px);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.panel-icon {
  font-size: 18px;
}

.character-actions {
  display: flex;
  gap: 8px;
}

.characters-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 4px;
  max-height: calc(100vh - 260px);
}

.character-item {
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #e4e7ed;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.character-item :deep(.el-card__body) {
  padding: 12px;
}

.character-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
  transform: translateY(-1px);
}

.character-item:hover :deep(.el-card__body) {
  background-color: #f0f9ff;
}

.character-content {
  display: flex;
  align-items: center;
  flex: 1;
  cursor: pointer;
}

.character-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 10px;
  flex-shrink: 0;
}

.character-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
}

.character-info {
  flex: 1;
}

.character-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
}

.character-meta {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 4px 0;
  flex-wrap: wrap;
}

.character-meta .age-text {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

.character-desc {
  font-size: 12px;
  color: #666;
  margin: 4px 0;
  line-height: 1.3;
  max-height: 2.6em;
  overflow: hidden;
  text-overflow: ellipsis;
}

.character-desc-truncated {
  cursor: help;
  transition: color 0.2s ease;
}

.character-tags {
  margin-top: 4px;
}

.character-tags .el-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.character-item .character-actions {
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

/* 批量生成相关样式 */
.batch-generate-content {
  max-height: 600px;
  overflow-y: auto;
}

.config-section,
.streaming-section,
.results-section {
  margin-bottom: 16px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.generated-characters-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
}

.generated-character-card {
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.generated-character-card:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.generated-character-card.selected {
  border-color: #67c23a;
  background: #f0f9ff;
}

.character-header {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  position: relative;
}

.character-avatar-preview {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.character-basic-info {
  flex: 1;
}

.character-basic-info h4 {
  margin: 0 0 4px 0;
  font-size: 13px;
  font-weight: 600;
}

.selection-indicator {
  position: absolute;
  right: 0;
  top: 0;
  color: #67c23a;
  font-size: 18px;
}

.character-details {
  font-size: 12px;
}

.detail-item {
  margin-bottom: 8px;
  line-height: 1.4;
}

.detail-item label {
  font-weight: 600;
  color: #606266;
}

.detail-item p {
  margin: 2px 0 0 0;
  color: #909399;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 16px;
}

.form-item-with-ai {
  position: relative;
}

.ai-button-group {
  display: flex;
  gap: 8px;
}

.character-type-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
</style>
